package com.sishu.njrtsdms.controller;

import com.sishu.njrtsdms.domain.core.LoginBody;
import com.sishu.njrtsdms.domain.core.LoginUser;
import com.sishu.njrtsdms.domain.core.R;
import com.sishu.njrtsdms.domain.vo.UserVO;
import com.sishu.njrtsdms.service.system.LoginService;
import com.sishu.njrtsdms.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class LoginController {


    private final LoginService loginService;

    public LoginController(LoginService loginService) {
        this.loginService = loginService;
    }


    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public R<?> login(@RequestBody LoginBody loginBody) {
        // 生成令牌
        var token = loginService
                .login(
                        loginBody.getUsername(),
                        loginBody.getPassword(),
                        loginBody.getCaptcha(),
                        loginBody.getCaptchaUUID()
                );
        return R.ok(token);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public R<UserVO> getInfo() {
        UserVO user = SecurityUtils.getLoginUserOptional()
                .map(LoginUser::getUser)
                .orElse(null);
        return R.ok(user);
    }
}
